package com.gdcp.controller.portal;

import com.gdcp.beans.*;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.*;
import com.gdcp.util.RandomNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/order/")
public class OrderController {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;
    @Autowired
    CartService cartService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    ShippingService shippingService;
    @Autowired
    OrderService orderServive;
    @Autowired
    CommentService commentService;

    @RequestMapping(value = "/myorder")
    public String member() {
        HttpServletRequest request=RequestHolder.getRequest();
        User user = (User) RequestHolder.getSession("user");
        List<Order> orders=orderService.queryAllById(user.getId());

        for (Order order:orders){
            List<OrderItem> orderItemList = orderItemService.queryOrderItemByOid(order.getOrder_no());
            for (OrderItem orderItem:orderItemList){
                Product product = productService.productInfoById(orderItem.getProduct_id());
                orderItem.setProduct(product);
                Comment comment=commentService.queryInfoById(orderItem.getUser_id(),orderItem.getProduct_id(),orderItem.getId());
                if (comment!=null){
                    Comment comment_info=commentService.queryInfoByParentId(comment.getId());
                    if (comment_info!=null){
                        comment.setReply(comment_info.getContent());
                    }
                }
                orderItem.setComment(comment);
            }
            order.setOrderItem(orderItemList);
        }

        request.setAttribute("orders",orders);
        return "frontend/myorder";
    }

    @Transactional(rollbackFor = { Exception.class })
    @RequestMapping(value = "/changeStatus",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> changeStatus(Integer oid,Integer status,String order_no){
        /*0-已取消(...), 10-未付款(), 20-已付款, 60-交易关闭(),订单*/
        /*0：都是已取消，10：都是未付款，20：下面，60：下面就是交易完成*/
        /*40-已发货(退货)，50-交易成功(评价,退货)，订单子项*/
        if (status==0||status==10||status==20||status==40||status==50||status==60){
            Order order=new Order();
            order.setId(oid);
            if (status==10) {
                order.setSend_time(new Date());
            }

            if (status==10){
                order.setStatus(20);
                order.setPayment_time(new Date());
            }else {
                order.setStatus(status);
            }
            //修改order
            int order_count=orderService.updateInformation(order);

            if(order_count<=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//就是这一句了，加上之后，如果doDbStuff2()抛了异常,
                return responseModel.setModel(false,status);
            }

            //修改orderItem
            /*0：都是已取消，10：都是未付款，20：下面，60：下面就是交易完成*/
            /*40-已发货(退货,确认收货)，50-交易成功(评价,退货)，订单子项*/
            List<OrderItem> orderItems=orderItemService.queryOrderItemByOid(order_no);
            for (OrderItem orderItem:orderItems){
                if (status==10){
                    orderItem.setUser_status(20);
                    orderItem.setShop_status(30);
                }else {
                    orderItem.setUser_status(status);
                    orderItem.setShop_status(status);
                }

                int orderItem_count=orderItemService.updateInformation(orderItem);
                if (orderItem_count<0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//就是这一句了，加上之后，如果doDbStuff2()抛了异常
                    return responseModel.setModel(false,status);
                }
            }

            return responseModel.setModel(true,status);
        }

        return responseModel.setModel(false,status);
    }

    @RequestMapping(value = "/deleteOrder",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> deleteOrder(Integer oid){
        int count=orderService.deleteById(oid);
        if (count>0){
            return responseModel.setModel(true,"删除成功");
        }
        return responseModel.setModel(false,"删除失败");
    }

    @Transactional(rollbackFor = { Exception.class })
    @RequestMapping(value = "/createOrder",method = RequestMethod.GET)
    public String createOrder(Integer address_id, Integer ciid , Integer status) {
        HttpServletRequest request=RequestHolder.getRequest();
        List<Cart> cartItems = (List<Cart>) RequestHolder.getSession("cartItems");

        User user = (User) RequestHolder.getSession("user");
        String orderNo= RandomNumberUtil.getRandomOrderNo();
        BigDecimal total= BigDecimal.valueOf(0);
        int totalNum = 0;
        //String sum=null;
        BigDecimal sumTotal= BigDecimal.valueOf(0);
        for (Cart cart:cartItems){
            OrderItem orderItem=new OrderItem();
            orderItem.setUser_id(user.getId());
            orderItem.setOrder_no(orderNo);
            orderItem.setProduct_id(cart.getProduct_id());
            orderItem.setUser_status(status);
            //支付
            if (status==20){
                orderItem.setShop_status(30);
            }
            //未支付
            if (status==10){
                orderItem.setShop_status(10);
            }
            orderItem.setQuantity(cart.getQuantity());

            orderItem.setProduct_name(cart.getProduct().getName());

            orderItem.setCurrent_unit_price(BigDecimal.valueOf(Double.valueOf(cart.getProduct().getPrice())));
            BigDecimal currentPrice=BigDecimal.valueOf(
                    Double.valueOf(cart.getProduct().getPrice())*cart.getQuantity()
            );
            total=total.add(currentPrice);
            orderItem.setTotal_price(String.valueOf(currentPrice));

            orderItem.setShop_id(cart.getProduct().getShop_id());
            orderItem.setProduct_image(cart.getProduct().getMain_image());
            int count=orderItemService.insert(orderItem);
            if (count<=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//就是这一句了，加上之后，如果doDbStuff2()抛了异常,
                return "frontend/product/index";
            }
            //System.out.println("ciid="+ciid+",cart");
            if (ciid!=-1) {
                //清空购物车相应商品
                cartService.deleteCartById(cart.getId());
            }
            //商品销量增加
            int productCount=productService.updateSaleCount(cart.getProduct_id());
            if (productCount<=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//就是这一句了，加上之后，如果doDbStuff2()抛了异常,
                return "frontend/product/index";
            }
            totalNum += cart.getQuantity();
            //sum = String.valueOf(cart.getQuantity());
            String quantity= String.valueOf(cart.getQuantity());
            String price= cart.getProduct().getPrice();
            BigDecimal quantity_big=new BigDecimal(quantity);
            BigDecimal price_big=new BigDecimal(price);
            BigDecimal sum = quantity_big.multiply(price_big);
            sumTotal = sumTotal.add(sum);
        }
//87   78
        Order order=new Order();
        order.setOrder_no(orderNo);
        order.setUser_id(user.getId());
        order.setShipping_id(address_id);

        order.setPayment(String.valueOf(total));
        order.setPayment_type(0);
        order.setPostage(5);

        if (status==20) {
            order.setPayment_time(new Date());
        }
        order.setStatus(status);
        Shipping shipping=shippingService.queryById(address_id);
        if (shipping.getReceiver_zip()!=null){
            order.setPostage(Integer.valueOf(shipping.getReceiver_zip()));
        }

        int count=orderService.insert(order);
        if (count<=0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "frontend/product/index";
        }

        request.setAttribute("totalNum", totalNum);
        request.setAttribute("sum", sumTotal);
        request.setAttribute("shipping_id", address_id);

        return "frontend/flow_end";
    }
}



/*@RequestMapping(value = "/deleteCart",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> deleteCart(Integer uid){
    List<Order> count=orderService.queryAllById(uid);
    if (count!=null){
        return responseModel.setModel(true,count);
    }

    return responseModel.setModel(false,"删除失败");
}
*/
/*List<Order> orders=orderService.queryAllById(user.getId());
        for (Order order02:orders){
            List<OrderItem> orderItemList = orderItemService.queryOrderItemByOid(order02.getOrder_no());
            order02.setOrderItem(orderItemList);
        }

        request.setAttribute("orders",orders);*/